const { query } = require("../utils/db");
const { v4: uuidv4 } = require("uuid");

// 获取部门列表
exports.getDepartmentList = async ({ page = 1, pageSize = 10, search }) => {
  const offset = (page - 1) * pageSize;
  let sql = `SELECT 
    FId, FName, FParentId, FCreatedAt, FUpdatedAt 
    FROM t_departments`;
  let countSql = "SELECT COUNT(*) as total FROM t_departments";
  let params = [];
  let countParams = [];

  if (search) {
    const searchParam = `%${search}%`;
    sql += " WHERE FName LIKE ?";
    countSql += " WHERE FName LIKE ?";
    params = [searchParam];
    countParams = [searchParam];
  }

  sql += " ORDER BY FCreatedAt DESC LIMIT ? OFFSET ?";
  params = params.concat([parseInt(pageSize), parseInt(offset)]);

  const departments = await query(sql, params);
  const totalResult = await query(countSql, countParams);

  // 获取树形结构
  const treeData = await buildDepartmentTree(departments);

  return {
    list: treeData,
    total: totalResult[0].total,
    page: parseInt(page),
    pageSize: parseInt(pageSize),
  };
};

// 构建部门树形结构
async function buildDepartmentTree(departments, parentId = null) {
  const tree = [];
  for (const dept of departments) {
    if (
      dept.FParentId === parentId ||
      (parentId === null && dept.FParentId === null)
    ) {
      const children = await buildDepartmentTree(departments, dept.FId);
      if (children.length > 0) {
        dept.children = children;
      }
      tree.push(dept);
    }
  }
  return tree;
}

// 获取单个部门详情
exports.getDepartmentById = async (FId) => {
  const departments = await query(
    `SELECT 
     FId, FName, FParentId, FCreatedAt, FUpdatedAt
     FROM t_departments WHERE FId = ? LIMIT 1`,
    [FId]
  );

  if (departments.length === 0) {
    throw { status: 400, message: "部门不存在" };
  }

  return departments[0];
};

// 创建部门
exports.createDepartment = async (departmentData) => {
  const { FName, FParentId } = departmentData;

  // 检查部门名称是否已存在
  const existing = await query(
    "SELECT FId FROM t_departments WHERE FName = ? LIMIT 1",
    [FName]
  );

  if (existing.length > 0) {
    throw { status: 400, message: "部门名称已存在" };
  }

  // 检查父部门是否存在
  if (FParentId) {
    const [parent] = await query(
      "SELECT FId FROM t_departments WHERE FId = ? LIMIT 1",
      [FParentId]
    );
    if (parent.length === 0) {
      throw { status: 400, message: "父部门不存在" };
    }
  }

  // 创建部门
  const result = await query(
    `INSERT INTO t_departments 
     (FName, FParentId)
     VALUES (?, ?)`,
    [FName, FParentId]
  );

  return { FId: result.insertId, FName, FParentId };
};

// 更新部门信息
exports.updateDepartment = async (FId, departmentData) => {
  // 检查部门是否存在
  const existing = await query(
    "SELECT FId FROM t_departments WHERE FId = ? LIMIT 1",
    [FId]
  );
  if (existing.length === 0) {
    throw { status: 400, message: "部门不存在" };
  }

  const { FName, FParentId } = departmentData;

  // 检查部门名称是否已存在（排除自己）
  const [existingName] = await query(
    "SELECT FId FROM t_departments WHERE FName = ? AND FId != ? LIMIT 1",
    [FName, FId]
  );

  if (existingName.length > 0) {
    throw { status: 400, message: "部门名称已存在" };
  }

  // 检查父部门是否存在
  if (FParentId) {
    const [parent] = await query(
      "SELECT FId FROM t_departments WHERE FId = ? LIMIT 1",
      [FParentId]
    );
    if (parent.length === 0) {
      throw { status: 400, message: "父部门不存在" };
    }

    // 检查是否设置自己为父部门
    if (FParentId == FId) {
      throw { status: 400, message: "不能设置自己为父部门" };
    }
  }

  const { affectedRows } = await query(
    `UPDATE t_departments SET 
     FName = ?, FParentId = ?, FUpdatedAt = CURRENT_TIMESTAMP 
     WHERE FId = ?`,
    [FName, FParentId, FId]
  );

  return affectedRows > 0;
};

// 删除部门
exports.deleteDepartment = async (FId) => {
  // 检查部门是否存在
  const existing = await query(
    "SELECT FId FROM t_departments WHERE FId = ? LIMIT 1",
    [FId]
  );
  if (existing.length === 0) {
    throw { status: 400, message: "部门不存在" };
  }

  // 检查是否有子部门
  const children = await query(
    "SELECT FId FROM t_departments WHERE FParentId = ? LIMIT 1",
    [FId]
  );
  if (children.length > 0) {
    throw { status: 400, message: "请先删除子部门" };
  }

  // 检查是否有用户关联
  const users = await query(
    "SELECT FUserId FROM t_user_departments WHERE FDepartmentId = ? LIMIT 1",
    [FId]
  );
  if (users.length > 0) {
    throw { status: 400, message: "请先移除部门下的用户" };
  }

  const { affectedRows } = await query(
    "DELETE FROM t_departments WHERE FId = ?",
    [FId]
  );

  return affectedRows > 0;
};

// 获取部门树形结构
exports.getDepartmentTree = async () => {
  const departments = await query(
    `SELECT 
     FId, FId as id, FName, FParentId 
     FROM t_departments 
     ORDER BY FParentId, FId`
  );

  return buildDepartmentTree(departments);
};
